# 此模块用于登录川藏平台
from utils import captcha_util
from utils import request_util
from utils import config_util
from utils import logging_method as log
from entity import crawler_config

# 验证码存放路径
img_path = config_util.root_path + "/img"


def download_captcha():
    """
    下载验证码图片到img文件夹
    :return:
    """
    response = request_util.get(crawler_config.get_conf("captcha_url"))
    captcha_path = "%s/%s.jpeg" % (img_path, crawler_config.get_conf("imgId"))
    with open(captcha_path, "wb") as image:
        image.write(response.content)
    return response


def login():
    """
    登录，失败后自动重试
    :return:
    """
    download_captcha()
    code = captcha_util.get_captcha_val()
    form_data = {
        "figure": crawler_config.get_conf("figure"),
        "username": crawler_config.get_conf("username"),
        "password": crawler_config.get_conf("password"),
        "imgId": crawler_config.get_conf("imgId"),
        "code": code
    }
    headers = {
        "Connection": "keep-alive",
        "Host": "sso.r93535.com",
        "cache-Control": "no-cache",
    }
    response = request_util.post(crawler_config.get_conf("login_url"), headers=headers, data=form_data)
    title = request_util.get_tile(response.text)
    if title == crawler_config.get_conf("wrong_title"):
        response = login()
    return response


def test_login_and_request():
    """
    测试登录和获取数据
    :return:
    """
    login()
    res = request_util.get("https://portal.r93535.com/czmh/apiportal/mgr/station/letter/count")
    log.info("测试结果1:", res.content)







